#include "StdAfx.h"
#include "FileKeyMgr.h"

#include "Entity/FileKey.h"
#include "dao/DAOFactory.h"
#include "dao/FileKeyDao.h"


CFileKeyMgr::CFileKeyMgr(void):m_bLoad(false)
{
	m_pFileKeyDao = CDAOFactory::GetFileKeyDao();
	InitializeCriticalSection(&m_cs);
}


CFileKeyMgr::~CFileKeyMgr(void)
{
	if(m_pFileKeyDao)
		delete m_pFileKeyDao;
	DeleteCriticalSection(&m_cs);
}




void  CFileKeyMgr::LoadFileKeyInfo()
{
	CFileKey *     pFileKey;
	EnterCriticalSection(&m_cs);
	if(m_bLoad)
	{
		LeaveCriticalSection(&m_cs);
		return;
	}

	do 
	{
		if(!m_pFileKeyDao->GetAllKey())
			break;
		pFileKey = new CFileKey;
		while(m_pFileKeyDao->EnumKey(*pFileKey))
		{
			m_fileKeyVector.push_back(pFileKey);
			pFileKey = new CFileKey;
		}

		if(pFileKey)
			delete pFileKey;

	} while (FALSE);

	m_bLoad = true;
	LeaveCriticalSection(&m_cs);
	return ;


}


void  CFileKeyMgr::ReLoadFileKeyInfo()
{
	EnterCriticalSection(&m_cs);
	Clear();
	LoadFileKeyInfo();
	LeaveCriticalSection(&m_cs);

}

bool  CFileKeyMgr::AddAKey(CFileKey*  pFileKey)
{

	bool bOk;
	if(pFileKey == NULL)
		return false;
	EnterCriticalSection(&m_cs);
	if(!m_bLoad)
	{
		LoadFileKeyInfo();
	}

	do 
	{
		if(!m_pFileKeyDao->AddAKey(*pFileKey))
		{
			delete pFileKey;
			bOk= false;
			break;
		}
		m_fileKeyVector.push_back(pFileKey);
		bOk = true;

	} while (false);

	LeaveCriticalSection(&m_cs);
	return bOk;

}




CFileKey*  CFileKeyMgr::GetFileKeyByHash(/*[int]*/CString& hashKey)
{
	if(hashKey == "")
		return NULL;
	EnterCriticalSection(&m_cs);
	if(!m_bLoad)
	{
		LoadFileKeyInfo();
	}

	FileKeyFinder  fileKeyFinder;
	fileKeyFinder.hashKey = hashKey;
	vector<CFileKey*>::iterator  it = std::find_if(m_fileKeyVector.begin(),m_fileKeyVector.end(),fileKeyFinder);
	if(it == m_fileKeyVector.end())
	{
		LeaveCriticalSection(&m_cs);
		return NULL;
	}
	LeaveCriticalSection(&m_cs);
	return (*it);

}


void   CFileKeyMgr::UnInit()
{
	EnterCriticalSection(&m_cs);
		if(m_pFileKeyDao)
			delete m_pFileKeyDao;
		m_pFileKeyDao = NULL;
		Clear();
	LeaveCriticalSection(&m_cs);
}


void  CFileKeyMgr::Clear()
{
	CFileKey*  pFileKey = NULL;
	EnterCriticalSection(&m_cs);
	while(m_fileKeyVector.size())
	{
		pFileKey = m_fileKeyVector.back();
		m_fileKeyVector.pop_back();
		if(pFileKey)
			delete  pFileKey;
	}
	m_bLoad = false;
	LeaveCriticalSection(&m_cs);

}